package cn.com.dcsgo.controller;

import jakarta.servlet.ServletContext;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 获取Servlet原生API
 *
 * @author Dcsgo
 * @since 2025/3/2 14:39
 */

@Controller
@RequestMapping("api")
public class ApiController {
    /**
     * 获取ServletContext
     * 直接注入即可，SpringMVC 在项目启动时就已经将ServletContext注入到容器中
     * 所以可以直接注入使用
     */
    private final ServletContext servletContext;

    public ApiController(ServletContext servletContext) {
        this.servletContext = servletContext;
    }

    /**
     * 获取 HttpServlet 原生对象很简单
     * 直接在形参列表中声明即可，SpringMVC 会自动注入
     *
     * @param request  request
     * @param response response
     * @param session  session
     * @return String
     */
    @ResponseBody
    @GetMapping("data")
    public String api(HttpServletRequest request,
                      HttpServletResponse response,
                      HttpSession session) {
        ServletContext servletContext1 = request.getServletContext();
        ServletContext servletContext2 = session.getServletContext();
        return servletContext.getServerInfo();
    }
}
